﻿namespace HZY.Framework.DynamicApiController;

/// <summary>
/// 自定义控制器扩展
/// </summary>
public static class DynamicApiControllerExtensions
{

    /// <summary>
    /// 自定义 api 控制器
    /// </summary>
    /// <param name="mvcBuilder"></param>
    /// <param name="action"></param>
    /// <returns></returns>
    public static IMvcBuilder AddDynamicApiController(this IMvcBuilder mvcBuilder, Action<DynamicApiControllerOptions>? action = null)
    {
        var apiControllerPlusOptions = new DynamicApiControllerOptions();

        action?.Invoke(apiControllerPlusOptions);

        mvcBuilder.ConfigureApplicationPartManager((applicationPartManager) =>
        {
            applicationPartManager.FeatureProviders.Add(new DynamicApiControllerFeatureProvider(apiControllerPlusOptions));
        });

        mvcBuilder.Services.Configure<MvcOptions>(mvcOptions =>
        {
            mvcOptions.Conventions.Add(new DynamicApiControllerApplicationModelConvention(apiControllerPlusOptions, mvcOptions));
        });

        return mvcBuilder;
    }

    /// <summary>
    /// 横线转驼峰命名
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static string HorizontalBarNamingHump(string name)
    {
        if (!name.Contains('-') && name != name.ToLower())
        {
            return name;
        }

        var sb = new StringBuilder();
        foreach (var item in name.Split("-", StringSplitOptions.RemoveEmptyEntries))
        {
            sb.Append(Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(item));
        }

        return sb.ToString();
    }

    /// <summary>
    /// 驼峰转横线命名
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static string HumpTurnBar(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            return input;
        }

        return Regex.Replace(input, @"([a-z0-9])([A-Z])", "$1-$2").ToLower();
    }

}
